package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginInterceptor
 * @Description TODO
 * @Author daoketa
 * @Version 1.0
 **/

public class RefreshInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取 token
        String token = request.getHeader("authorization");

        // 2.判断有无 token
        if (StrUtil.isBlank(token)){
            return true;
        }

        // 3.保存 UserDto 到 ThreadLocal
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> targetMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        if (targetMap == null || targetMap.isEmpty()){
            return true;
        }
        // 转换
        UserDTO userDTO = BeanUtil.fillBeanWithMap(targetMap, new UserDTO(), false);
        // 保存
        UserHolder.saveUser(userDTO);
        // 刷新有效期
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
